import { userApi, type UserInfo } from '~/utils/api/user-api';

export const userInfoStorage = useSessionStorage<User>('user', null, {
	serializer: {
		read: v => JSON.parse(v),
		write: v => JSON.stringify(v),
	},
});
export const reTokenStorage = useLocalStorage('reToken', '');

interface User {
	userInfo?: UserInfo;
	accessToken?: string;
	refreshToken?: string;
}

interface UserStoreState {
	user?: User;
}

/**
 * 用户信息仓库
 */
export const useUserStore = defineStore('userStore', {
	state: (): UserStoreState => ({
		user: undefined,
	}),
	actions: {
		// 登录
		setUser(value: User) {
			this.user = { ...this.user, ...value };
			userInfoStorage.value = this.user;
			if (value.refreshToken) {
				reTokenStorage.value = value.refreshToken;
			}
		},
		// 登出
		logout() {
			userApi.logout().then();
			this.user = undefined;
			userInfoStorage.value = null;
			reTokenStorage.value = '';
			useRouter().push('/login').then();
		},
	},
	getters: {
		// 获取用户登录状态，如果user不为undefined则表示已登录
		isLogin: (state: UserStoreState) => state.user !== undefined,
	},
});
